const express = require('express')
const router = express.Router()
const bcrypt = require('bcrypt')
const passport = require('passport')
const User = require('../../models/User')
const pagination = require('mongoose-sex-page')

router.get('/user/list', passport.authenticate('jwt', { session: false }), (req, res) => {
  let userFields = {}
  if (req.query.name) userFields.name = req.query.name
  if (req.query.number) userFields.number = req.query.number
  if (req.query.telephone) userFields.telephone = req.query.telephone
  if (req.query.sex) userFields.sex = req.query.sex
  if (req.query.age) userFields.age = req.query.age
  if (req.query.role) userFields.role = req.query.role
  if (req.query.UserAddress) userFields.UserAddress = req.query.UserAddress
  // page 当前页
  pagination(User)
    .find(userFields)
    .page(req.query.pageNum)
    .size(req.query.pageSize)
    .exec()
    .then((user) => {
      if (!user) {
        return res.status(400).json({ status: 400, message: '获取用户列表失败', data: [] })
      }
      const total = user.length
      return res.json({ status: 200, message: '请求成功', success: true, data: user, total })
    })
    .catch((error) => {
      return res.status(400).json({ status: 400, error, message: '获取列表失败' })
    })
})
// jwt的一个插件库
router.post('/user/add', passport.authenticate('jwt', { session: false }), (req, res) => {
  const userFields = {}
  if (req.body.name) userFields.name = req.body.name
  if (req.body.sex) userFields.sex = req.body.sex
  if (req.body.age) userFields.age = req.body.age
  if (req.body.password) userFields.password = req.body.password
  if (req.body.number) userFields.number = req.body.number
  if (req.body.telephone) userFields.telephone = req.body.telephone
  userFields.UserAddress = req.body.UserAddress
  if (req.body.role) userFields.role = req.body.role
  // console.log(userFields)
  // 查询数据库中是否拥有邮箱
  User.findOne({ number: req.body.number }).then((user) => {
    if (user) {
      return res.status(400).json({ status: '400', message: '此身份证号已经被注册!' })
    } else {
      const newUser = new User(userFields)
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          // Store hash in your password DB.
          if (err) throw err
          newUser.password = hash
          newUser
            .save()
            .then(() => {
              return res.json({ status: 200, success: true, message: '用户注册成功' })
            })
            .catch((error) => {
              return res.status(400).json({ status: 400, error, message: '注册失败' })
            })
        })
      })
    }
  })
})

router.post('/user/edit/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
  let userField = {}
  if (req.body.name) userField.name = req.body.name
  if (req.body.college) userField.college = req.body.college
  if (req.body.telephone) userField.telephone = req.body.telephone
  if (req.body.sex) userField.sex = req.body.sex
  if (req.body.age) userField.age = req.body.age
  if (req.body.role) userField.role = req.body.role
  if(req.body.UserAddress) userField.UserAddress=req.body.UserAddress
  User.findOneAndUpdate({ _id: req.params.id }, { $set: userField }, { new: true })
    .then(() => {
      // user.save().then(user => res.json(user));
      return res.json({ status: 200, success: true, message: '修改成功' })
    })
    .catch((error) => {
      return res.status(400).json({ status: 400, error, message: '修改失败!' })
    })
})

router.post('/user/editpwd/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
  let userField = {}
  User.findOne({ _id: req.params.id }).then((user) => {
    // 密码匹配
    bcrypt.compare(req.body.oldpwd, user.password).then((isMatch) => {
      if (isMatch) {
        userField.password = req.body.newpwd
        const updateUser = User.findOneAndUpdate({ _id: req.params.id }, { $set: userField }, { new: true })
        console.log(updateUser._update.$set.password)
        bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(updateUser._update.$set.password, salt, (err, hash) => {
            // Store hash in your password DB.
            if (err) throw err
            updateUser._update.$set.password = hash
            updateUser
              .then(() => {
                return res.json({ status: 200, success: true, message: '修改密码成功' })
              })
              .catch((error) => {
                return res.status(400).json({ status: 400, error, message: '修改失败' })
              })
          })
        })
      } else {
        return res.status(400).json({ status: 400, message: '修改失败', error: '密码不正确，请重新输入' })
      }
    })
  })
})

router.delete('/user/delete/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
  User.findOneAndDelete({ _id: req.params.id })
    .then((user) => {
      // user.save().then(user => res.json(user));
      return res.json({ status: 200, success: true, message: '删除成功' })
    })
    .catch((error) => {
      return res.status(400).json({ status: 400, error, message: '删除失败!' })
    })
})

router.get('/user/detail/:id', passport.authenticate('jwt', { session: false }), (req, res) => {
  User.findOne({ _id: req.params.id })
    .then((user) => {
      return res.json({ status: 200, message: '请求成功', success: true, data: user })
    })
    .catch((error) => {
      return res.status(400).json({ status: 400, message: ' 获取信息失败', error })
    })
})

module.exports = router
